package com.hdy.net.order;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class DGJRetrofitClient implements IRetrofitClient{
    private PosApiService apiService;
    private Retrofit retrofit;

    public DGJRetrofitClient(String baseUrl, OkHttpClient client) {
        retrofit = new Retrofit.Builder()
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(baseUrl)
                .build();
        apiService = create(PosApiService.class);
    }

    public  <T> T create(final Class<T> service) {
        if (service == null) {
            throw new RuntimeException("Api service is null!");
        }
        return retrofit.create(service);
    }

    @Override
    public void login(String url, RequestBody jsonStr, Subscriber subscriber) {
        apiService.login(url, jsonStr)
                .compose(schedulersTransformer())
                .subscribe(subscriber);
    }

    @Override
    public void getBasicData(String url, RequestBody jsonStr, Subscriber subscriber) {
        apiService.getBasicData(url, jsonStr)
                .compose(schedulersTransformer())
                .subscribe(subscriber);
    }

    @Override
    public void order(String url, RequestBody jsonStr, Subscriber subscriber) {
        apiService.order(url, jsonStr)
                .compose(schedulersTransformer())
                .subscribe(subscriber);
    }

    @Override
    public void getOrderInfo(String url, RequestBody jsonStr, Subscriber subscriber) {
        apiService.getOrderInfo(url, jsonStr)
            .compose(schedulersTransformer())
            .subscribe(subscriber);
    }

    Observable.Transformer schedulersTransformer() {
        return new Observable.Transformer() {

            @Override
            public Object call(Object observable) {
                return ((Observable)  observable).subscribeOn(Schedulers.io())
                        .unsubscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }

    public static <T> T execute(Observable<T> observable ,Subscriber<T> subscriber) {
        observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

        return null;
    }
}
